package cn.tedu.zx.sso.controller;

import cn.tedu.zx.common.restful.JsonResult;
import cn.tedu.zx.sso.pojo.dto.AdminLoginDTO;
import cn.tedu.zx.sso.pojo.vo.TokenVO;
import cn.tedu.zx.sso.security.service.amdin.IAdminSSOService;
import cn.tedu.zx.sso.util.LoginUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

//管理员单点登录控制器
@RestController
@RequestMapping("/admin/sso")
@Api(tags="后台管理用户认证")
@Slf4j
public class AdminSSOController {
    @Autowired
    private IAdminSSOService adminSSOService;
    @Value("${jwt.tokenHead}")
    private String jwtTokenHead;

    @ApiOperation(value = "后台单点登录认证登录")
    @PostMapping("/login")
    public JsonResult<TokenVO> doLogin(@Valid AdminLoginDTO adminLoginDTO, HttpServletRequest request){
        String remoteAddr= LoginUtils.getIpAddress(request);
        log.info("远程ip地址：{}",remoteAddr);
        String userAgent=request.getHeader("User-Agent");
        log.info("远程客户端：{}",userAgent);
        adminLoginDTO.setIp(remoteAddr);
        adminLoginDTO.setUserAgent(userAgent);
        String token = adminSSOService.doLogin(adminLoginDTO);
        TokenVO tokenVO = new TokenVO();
        tokenVO.setTokenHeader(jwtTokenHead);
        tokenVO.setTokenValue(token);
        return JsonResult.ok(tokenVO);
    }


    @ApiOperation(value = "后台单点登录认证登出")
    @PostMapping("/logout")
    public JsonResult doLogout(@RequestHeader(name ="Authorization") String token){
        adminSSOService.doLogout(token);
        return JsonResult.ok();
    }
}
